package tree.leetcode_99;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

public class DFS {
    public void recoverTree(TreeNode root) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;
        TreeNode first = null;
        TreeNode second = null;
        TreeNode pre = null;
        while (!stack.isEmpty() || cur != null) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if (pre != null && pre.val > cur.val) {
                if (first == null) {
                    // 记录第一个错误节点
                    first = pre;
                }
                // 记录第二个错误节点
                second = cur;
            }
            pre = cur;
            cur = cur.right;
        }
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
    }
}
